const path = require('path')
const colors = require('colors-console')
const nodeExternals = require('webpack-node-externals');
const webpack = require('webpack')
const BytenodePlugins = require('./bytenode-plugins')



function getCompiler(env) {
  const compiler = webpack({
    mode: env === 'prod' ? 'production' : 'development',
    entry: path.resolve(__dirname, '../src/main/index.ts'),
    target: 'electron-main',
    node: {
      __dirname: false,
    },
    output: {
      path: path.join(__dirname, '../dist'),
      filename: 'main.js'
    },
    // 排除node_modules中的模块，只保留require('module'), 也可以通过参数来指定需要忽略的node_modules模块
    externals: [nodeExternals()],
    resolve: {
      // 自动给文件加上后缀
      extensions: ['.ts', '.tsx']
    },

    module: {
      rules: [
        {
          test: /\.node$/,
          loader: "node-loader"
        },
        {
          test: /\.ts$/,
          loader: 'ts-loader',
          options: {
            transpileOnly: true,
          },
        }
      ]
    },
    plugins: env === 'prod' ?
      [new BytenodePlugins()] :
      []
  })

  return compiler
}


async function buildMain(env) {
  const compiler = getCompiler(env)
  return new Promise((resolve, reject) => {
    compiler.run((err, status) => {
      if (!err) {
        console.log(colors('green', '主进程代码编译成功'))
        resolve()
      } else {
        console.log(colors('red', '主进程代码编译失败'))
        reject(err)
      }
    })
  })
}

// run()

// run()
// setTimeout(() => {
// }, 10000)

module.exports = {
  buildMain
}